package JAVA300.第十二章网络编程;

import java.io.*;
import java.net.Socket;

/**
 * 客户端中的发送端
 * 1。获取控制台消息封装
 * 2。发送方法封装
 * 3。释放资源
 * 4。run
 */

public class web_TCPChatSend implements Runnable{
    private  BufferedReader console ;
    private DataOutputStream dos;
    private Socket socket;
    private boolean isRunning;
    private String sendname;

    public web_TCPChatSend(Socket socket,String name) {
        this.sendname = name;
        this.socket = socket;
        this.isRunning = true;

        try {
            console= new BufferedReader(new InputStreamReader(System.in));
            dos= new DataOutputStream(socket.getOutputStream());
            //****发送名称
            send(sendname);
        } catch (IOException e) {
           // e.printStackTrace();
            System.out.println("-----client send---");
            release();
        }
    }



    //从控制台取得消息
    private String getMsgFromConsole(){
        try {
            return console.readLine();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }

    //发送消息
    private void send(String sendMsg){
        try {
            dos.writeUTF(sendMsg);
            dos.flush();
        } catch (IOException e) {
            System.out.println("---error Client send1-----");
            release();
        }
    }

    //释放资源-释放资源-借助带有可变参数的工具类函数进行封装
    private void release(){
        this.isRunning = false;
        web_TCPChatUntils.close(dos,console,socket);

    }


    @Override
    public void run() {
        while (isRunning){

            String msg = getMsgFromConsole();
            if (!msg.equals("")){
                send(msg);

            }else {
                send("");
            }

        }

    }
}
